package com.anbinh.doctor.fragment.benhnhan;

import java.io.File;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.anbinh.doctor.R;
import com.anbinh.doctor.adapter.AccountAdapter;
import com.anbinh.doctor.adapter.PermissionDetailtAdapter;
import com.anbinh.doctor.model.ItemMeu;
import com.anbinh.doctor.model.NewAvatar;
import com.anbinh.doctor.model.ResponsePatient.Patient;
import com.anbinh.doctor.model.UserLogin;
import com.anbinh.doctor.request.controller.ServerController;
import com.anbinh.doctor.service.request.OnRequest;
import com.anbinh.doctor.utils.Utils;
import com.lsjwzh.widget.materialloadingprogressbar.CircleProgressBar;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

public class FragmentPatientDetailt extends Fragment {
	private static FragmentPatientDetailt fragment = null;
	private View mView;
	private CircleProgressBar loadding;
	public final static int REQ_EDIT_AVATAR = 122;
	public final static int REQ_ATTACH_FILE = 2;
	private ImageView avatar;
	private UserLogin userLogin;
	private TextView lblName;
	private PermissionDetailtAdapter adapter;
	private ListView mListview;
	protected ItemMeu currentMenu;
	private ArrayList<ItemMeu> mList;
	private TextView lblTuoi;
	private TextView lblGender;
	private TextView lblBrithday;

	public static FragmentPatientDetailt newInstance() {
		if (fragment == null) {
			fragment = new FragmentPatientDetailt();
		}
		return fragment;
	}

	@Override
	public void onResume() {
		super.onResume();

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.fragment_message, null);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		userLogin = Utils.getAccountModel(getActivity(), Utils.KEY_USER);

		mListview = (ListView) mView.findViewById(R.id.listView1);
		View header = getActivity().getLayoutInflater().inflate(
				R.layout.header_patients, null);
		mListview.addHeaderView(header);
		loadding = (CircleProgressBar) header.findViewById(R.id.loadding);
		Patient assistants = FragmentListPatients.newInstance()
				.getCurrentPatient();
		lblName = (TextView) header.findViewById(R.id.lblName);
		lblBrithday = (TextView) header.findViewById(R.id.lblBrithday);
		lblGender = (TextView) header.findViewById(R.id.lblGender);
		lblTuoi = (TextView) header.findViewById(R.id.lblTuoi);

		lblBrithday.setText(assistants.getBirth_date());
		lblGender.setText(assistants.getGender());
		lblName.setText(assistants.getPatient_name());

		if (!assistants.getBirth_date().isEmpty()) {
			String firtYear[] = assistants.getBirth_date().split("-");
			if(firtYear.length==3){
				int tuoi = Integer.parseInt(Utils.getCurrentYear())
						- Integer.parseInt(firtYear[2]);
				lblTuoi.setText(String.format(
						getResources().getString(R.string.tuoi), tuoi));
			}
		}

		avatar = (ImageView) header.findViewById(R.id.avatar);
		avatar.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				pickFile(getActivity(), REQ_EDIT_AVATAR);
			}
		});
		ImageLoader imageLoader = ImageLoader.getInstance();
		imageLoader.init(ImageLoaderConfiguration.createDefault(getActivity()
				.getApplicationContext()));

		Bitmap bmp = imageLoader.loadImageSync(assistants.getAvatar());
		if (bmp == null) {

			imageLoader.displayImage(assistants.getAvatar(), avatar,
					Utils.getOptions(getActivity()),
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingStarted(String imageUri, View view) {
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
						}

						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
						}
					});
		} else {
			avatar.setImageBitmap(bmp);
		}

		mList = Utils.getMenu(getActivity(), R.menu.patient_detailt);
		AccountAdapter adapter = new AccountAdapter(getActivity(),
				R.layout.item_account, mList);
		mListview.setAdapter(adapter);

		mListview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position == 0)
					return;
				currentMenu = mList.get(position - 1);
				onClickItem(position - 1);
			}
		});
	}

	public ItemMeu getCurrentPermission() {
		return currentMenu;
	}

	public void updateInfo(Intent data) {
		final UserLogin user = Utils.getAccountModel(getActivity(),
				Utils.KEY_USER);

		String token = user.getData().getToken();
		Uri selectedImage = data.getData();
		avatar.setImageURI(selectedImage);
		File file = new File(Utils.getRealPathFromURI(getActivity(),
				selectedImage));
		loadding.setVisibility(View.VISIBLE);
		Utils.disableEnableControls(false, mView);
		ServerController.getInstance(getActivity()).requestUploadAvatar(token,
				file, new OnRequest<NewAvatar>() {

					@Override
					public void onSuccess(NewAvatar data) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						if (data.getResponsecode() >= 0) {
							userLogin.getData().getUserInfo()
									.setAvatar(data.getData().getNewAvatar());
							Utils.updateData(getActivity(), Utils.KEY_USER,
									userLogin);
							Intent intent = new Intent();
							intent.putExtra(Utils.KEY, Utils.ONRESUME_BIEU_HIEN);
							getActivity().setResult(Integer.MAX_VALUE, intent);
							getActivity().finish();
						}
					}

					@Override
					public void onError(int errorCode, String message) {
						loadding.setVisibility(View.GONE);
						Utils.disableEnableControls(true, mView);
						Utils.showMessage(getActivity(), message);
					}
				});
	}

	public void pickFile(Activity activity, int requestCode) {
		Intent intent = new Intent(Intent.ACTION_PICK);

		// TODO Auto-generated method stub
		// call android default gallery
		intent.setType("image/*");
		// ******** code for crop image
		activity.startActivityForResult(intent, requestCode);

	}

	public void onClickItem(int position) {
		Bundle bundle = new Bundle();
		int id = mList.get(position).getRegId();
		bundle.putInt(Utils.KEY, id);
		// if (id == R.id.cac_van_de_suc_khoe||id ==
		// R.id.lich_su_benh_cua_gia_dinh||id == R.id.lich_su_kham_chua_benh) {
		bundle.putBoolean(Utils.CUSTOMBAR, false);
		/*
		 * } else { bundle.putBoolean(Utils.CUSTOMBAR, true); }
		 */
		bundle.putString(Utils.TITLE, mList.get(position).getTitle());
		Utils.getNewIntent(getActivity(), bundle);
	}

}
